const express = require('express')
const router = express.Router()
const multer = require('multer')

var storage = multer.diskStorage({
    //设置上传后文件路径，upload文件夹会自动创建
    destination: function (req, file, cb) {
       cb(null, './public/img') 
    },
    //给上传文件重命名，获取添加后缀名
    filename: function (req,  file, cb) {
        var fileFormat = (file.originalname).split(".");
        //给图片加上时间戳格式防止重名
        //把 abc.jpg图片切割成数据[abc, jpg],然后用数组长度减1来获取后缀名
        // cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]); //文件名带imgKey-
        cb(null,  Date.now() + "." + fileFormat[fileFormat.length - 1]);

    }
});

var upload = multer({
    storage: storage
});

//图片上传
/**
 * @apiGroup File
 * @api {post} /file/upload 菜品图片添加
 * @apiName upload
 * @apiParam {String} imgKey 图片key值
 */
router.post('/upload', upload.single('imgKey'), (req, res)=>{
    //imgKey 要上传图片的key值,必须与前端保持统一
    let {size, mimetype, path} = req.file
    let types = ['jpg', 'jpeg', 'png', 'gif']
    let tmpType = mimetype.split('/')[1]

    if(size >= 500000){
        return res.send({err: -1, msg: '图片尺寸过大'})
    }else if(types.indexOf(tmpType) == -1){
        return res.send({err: -2, msg: '图片类型错误'})
    }else{
        let url = `/public/img/${req.file.filename}`
        res.send({err: 0, msg: '上传成功', img: url})
        // console.log(req.file)
    }
})

module.exports = router